package com.evil.common.file.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.regex.Pattern;

/**
 * @author liyang
 */
@AllArgsConstructor
public enum FileTypeEnum {
    /**
     * 文件类型
     */
    OTHER(0, "其他", "file", null),
    IMAGE(1, "图片", "image", ".+(jpeg|jpg|gif|png|bmp)$"),
    VIDEO(2, "视频", "video", ".+(mp4|flv|rmvb|3gp|avi|wmv|swf|mov)$"),
    VOICE(3, "语音", "voice", ".+(mp3|m4a|flac|wav)$"),
    FOLDER(99, "文件夹", "folder", null),
    ;

    @Getter
    int id;
    @Getter
    String title;
    @Getter
    String name;
    @Getter
    String pattern;

    public static FileTypeEnum getById(Integer id) {
        if (id == null) {
            return null;
        }
        FileTypeEnum[] enums = values();
        for (FileTypeEnum e : enums) {
            if (e.getId() == (id)) {
                return e;
            }
        }
        return null;
    }

    public static String getNameByExtension(String extension) {
        if (extension != null) {
            for (FileTypeEnum e : values()) {
                if (null != e.getPattern() && Pattern.matches(e.getPattern(), extension)) {
                    return e.name;
                }
            }
        }
        return OTHER.getName();
    }

    public static Integer getIdByExtension(String extension) {
        if (extension != null) {
            extension = extension.toLowerCase();
            extension = extension.startsWith(".") ? extension : "." + extension;
            for (FileTypeEnum e : values()) {
                if (null != e.getPattern() && Pattern.matches(e.getPattern(), extension)) {
                    return e.id;
                }
            }
        }
        return OTHER.id;
    }

    public static String getNameById(Integer id) {
        FileTypeEnum e = getById(id);
        return e == null ? "" : e.getTitle();
    }
}
